/*
 * Copyright (c) 2024 Shenzhen Kaihong Digital Industry Development Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

 #include "cJSON.h"
 #include "reply_handler.h"
 #include "iot_connect_log.h"
namespace OHOS {
namespace iotConnect {
void ReplyHandler::SubThingModelReplyHandler(const SubThingModelExecResult res, const std::string& msgId, 
    const std::string& svcId, const std::string& devId, const char *data, const uint32_t len)
{
#if IOTC_CONF_DEV_TYPE == 2
    IotcCharState reportInfo;
    reportInfo.msgId = msgId.c_str();
    reportInfo.svcId = svcId.c_str();
    reportInfo.devId = devId.c_str();
    if(nullptr == data && res == SubThingModelExecResult::SUB_MODEL_TIMEOUT) {
        cJSON *json = cJSON_CreateObject();
        if (json == NULL) {
            HILOGE("create obj error");
            return;
        }

        if (cJSON_AddNumberToObject(json, "errorCode", res) == NULL) {
            cJSON_Delete(json);
            HILOGE("add result error");
            return;
        }

        reportInfo.data = cJSON_PrintUnformatted(json);
        reportInfo.len = strlen(reportInfo.data);
        int ret = IotcOhDevReportCharState(&reportInfo, 1);
        if (ret != 0) {
            cJSON_Delete(json);
            HILOGE("IotcOhDevReportCharState error");
            return;
        }

        cJSON_Delete(json);
    } else {
        cJSON *json = cJSON_ParseWithLength((char *)data, len);
        if(nullptr == json) {
            HILOGE("create json error");
            return;
        }
        cJSON_DeleteItemFromObject(json, "msgSeq");

        if (cJSON_AddNumberToObject(json, "errorCode", res) == NULL) {
            cJSON_Delete(json);
            HILOGE("add result error");
            return;
        }
        reportInfo.data = cJSON_PrintUnformatted(json);
        reportInfo.len = strlen(reportInfo.data);

        int ret = IotcOhDevReportCharState(&reportInfo, 1);
        if (ret != 0) {
            cJSON_Delete(json);
            HILOGE("IotcOhDevReportCharState error");
            return;
        }

        cJSON_Delete(json);
    }
#endif
}
}
}